﻿import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { OrganizationUnitDto, PasswordComplexitySetting, ProfileServiceProxy, UserRoleDto, UserServiceProxy, UsableRangeDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { StandardPartsFeatureDto,UsingFormDetailDto, UsingFormServiceProxy,UsingFormState,UsingFormDetailExeInput,RoleUserServiceProxy,ImportAllotDto } from '@shared/service-proxies/service-proxies';
import { AbpSessionService } from '@abp/session/abp-session.service';
@Component({
    selector: 'fetchImportRequirementGetAllEditComponent',
    templateUrl: './fetch-import-requirement-getall_edit.component.html'
})
export class FetchImportRequirementGetAllEditComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    canChangeUserName = true;
    isTwoFactorEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled');
    isLockoutEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled');
    passwordComplexitySetting: PasswordComplexitySetting = new PasswordComplexitySetting();

    //user: UserEditDto = new UserEditDto();
    roles: UserRoleDto[];
    sendActivationEmail = true;
    setRandomPassword = true;
    passwordComplexityInfo = '';
    profilePicture: string;

    allOrganizationUnits: OrganizationUnitDto[];
    memberedOrganizationUnits: string[];
    editFlag = true;
    usingFormDtoStateOption:object[];// 审核状态

    userName:string;
    userId:string;
    authorityUserOption:Array<object>;
    parentRecords:Array<ImportAllotDto>;
    

    constructor(
        injector: Injector,
        private _userService: UserServiceProxy,
        private _usingFormServiceProxy: UsingFormServiceProxy,
        private _roleUserServiceProxy:RoleUserServiceProxy,
        private _sessionServiceProxy: AbpSessionService,
        private _profileService: ProfileServiceProxy
    ) {
        super(injector);
        this.usingFormDtoStateOption = new Array();
        this.usingFormDtoStateOption.push({value:0,text:UsingFormState[0]});
        this.usingFormDtoStateOption.push({value:1,text:UsingFormState[1]});
        this.usingFormDtoStateOption.push({value:2,text:UsingFormState[2]});
        this.usingFormDtoStateOption.push({value:3,text:UsingFormState[3]});
        this.getAuthorityUserOption();
    }
        /**
     * 获取有权限的用户
     */
    getAuthorityUserOption() {
        this.authorityUserOption = new Array<object>()
        // 车间审批领导
        this._roleUserServiceProxy.getUsersByRole(0)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.authorityUserOption = result;
            });
    }
    uuid() {
        var uuidValue = "", k, randomValue;
        for (k = 0; k < 32;k++) {
          randomValue = Math.random() * 16 | 0;
      
          if (k == 8 || k == 12 || k == 16 || k == 20) {
            uuidValue += "-"
          }
          uuidValue += (k == 12 ? 4 : (k == 16 ? (randomValue & 3 | 8) : randomValue)).toString(16);
        }
        return uuidValue;
      }
    show(_pParentRecords:Array<ImportAllotDto>): void {
        if(_pParentRecords == null || _pParentRecords.length == 0){
            return;
        }
        this.parentRecords = _pParentRecords;
        this.active = true;
        this.modal.show();
    }

    setPasswordComplexityInfo(): void {

        this.passwordComplexityInfo = '<ul>';

        if (this.passwordComplexitySetting.requireDigit) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireDigit_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireLowercase) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireLowercase_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireUppercase) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireUppercase_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireNonAlphanumeric) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireNonAlphanumeric_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requiredLength) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequiredLength_Hint', this.passwordComplexitySetting.requiredLength) + '</li>';
        }

        this.passwordComplexityInfo += '</ul>';
    }

    getProfilePicture(profilePictureId: string): void {
        if (!profilePictureId) {
            this.profilePicture = this.appRootUrl() + 'assets/common/images/default-profile-picture.png';
        } else {
            this._profileService.getProfilePictureById(profilePictureId).subscribe(result => {

                if (result && result.profilePicture) {
                    this.profilePicture = 'data:image/jpeg;base64,' + result.profilePicture;
                } else {
                    this.profilePicture = this.appRootUrl() + 'assets/common/images/default-profile-picture.png';
                }
            });
        }
    }

    onShown(): void {
        document.getElementById('id').focus();
    }

    save(): void {
        this.primengTableHelper.showLoadingIndicator();
        this.saving = true;
        if(this.parentRecords.length > 0){
            let record:ImportAllotDto= this.parentRecords[0];
            let usingFormDetailDto = new UsingFormDetailDto();
            usingFormDetailDto.serialNumber = record.serialNumber;
            usingFormDetailDto.quantityOfUsing = record.usingOfQuantity;

            let standardPartsFeatureDto = new StandardPartsFeatureDto();
            standardPartsFeatureDto.displayName = record.name;
            standardPartsFeatureDto.materials = record.materials;
            standardPartsFeatureDto.specification = record.specification;
            standardPartsFeatureDto.standardNumber = record.standard;
            usingFormDetailDto.features = standardPartsFeatureDto;

            let usableRangeDto = new UsableRangeDto();
            usableRangeDto.batch = record.batch;
            usableRangeDto.belongToComponent = record.part;
            usableRangeDto.belongToModel = record.model;
            usableRangeDto.unitOfUsing = record.dpt;
            usingFormDetailDto.usableRange = usableRangeDto;
            usingFormDetailDto.taskNumber = record.taskNum;
            
            this._usingFormServiceProxy.createOrUpdateDetailInfo(usingFormDetailDto)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(result => {
                this.submit(result);
            });  
        }
    }
    submit(id): void {
        var usingFormDetailExeInput = new UsingFormDetailExeInput();
        usingFormDetailExeInput.id = id;
        usingFormDetailExeInput.userId = this.userId;
        this._usingFormServiceProxy.toExamine(usingFormDetailExeInput)
        .pipe(finalize(() => { }))
        .subscribe(() => {
            this.notify.info(this.l('SavedSuccessfully'));
            // 删除第一个
            this.parentRecords.splice(0,1);
            if(this.parentRecords.length == 0){
                this.close();
                this.modalSave.emit(null);
                this.primengTableHelper.hideLoadingIndicator();
                return;
            }
            // 执行下一个
            this.save();
        });

       
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getAssignedRoleCount(): number {
        return _.filter(this.roles, { isAssigned: true }).length;
    }
}
